﻿using System;
using System.Configuration;
using System.IO;

namespace ADC.Comet.Core
{
    /// <summary>
    /// 文件日志组件
    /// </summary>
    public class FileLogger  
    {
        /// <summary>
        /// 排他锁对象
        /// </summary>
        protected static object LockObject = new object();
        /// <summary>
        /// 日志文件路径
        /// </summary>
        protected readonly string FilePath ;
        /// <summary>
        /// 构造方法
        /// </summary>
        public FileLogger()
        {
            //读取配置日志文件路径,否则使用当前路径
            FilePath = ConfigurationManager.AppSettings["LogFilePath"]; 
            FilePath = string.Format("{0}/{1}.log ", string.IsNullOrEmpty(FilePath) ? AppDomain.CurrentDomain.BaseDirectory : FilePath, DateTime.Now.ToString("yyyy-MM-dd"));
        }
        /// <summary>
        /// 写入文件
        /// </summary>
        /// <param name="content"></param>
        protected void Write(string content)
        {
            lock (LockObject)
            {
                using (var st = File.AppendText(FilePath))
                {
                    st.Write(content);
                }
            }
        }
        /// <summary>
        /// 写入消息
        /// </summary>
        /// <param name="msg"></param>
        public void Info(string msg)
        {
            var content = string.Format("【{0}】{1}\r\n", DateTime.Now.ToString("hh:mm:ss"), msg);
            Write(content);
        }
        /// <summary>
        /// 写入调试信息
        /// </summary>
        /// <param name="msg"></param>
        public void Debug(string msg)
        {
            var content = string.Format("【{0}】DEBUG!{1}\r\n", DateTime.Now.ToString("hh:mm:ss"), msg);
            Write(content);
        }
        /// <summary>
        /// 写入警告
        /// </summary>
        /// <param name="msg"></param>
        public void Warn(string msg)
        {
            var content = string.Format("【{0}】WARN!{1}\r\n", DateTime.Now.ToString("hh:mm:ss"), msg);
            Write(content);
        }
        /// <summary>
        /// 写入警告
        /// </summary>
        /// <param name="ex"></param>
        /// <param name="msg"></param>
        public void Error(Exception ex, string msg)
        {
            var content = string.Format("【{0}】ERROR!{1};Message:{2}\r\n", DateTime.Now.ToString("hh:mm:ss"), msg,ex);
            Write(content);
        }
    }
}